package myapps.ttclient.asymmetric_encryption;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


import android.content.Context;

public class RSAManager {

	private Context context;

	public RSAManager(Context context) {
		this.context = context;

	}
	
	public void test() throws IOException {
		BigInteger server_exponent = getBigIntegerFromFile("server_exponent.txt");
		BigInteger server_modulus = getBigIntegerFromFile("server_modulus.txt");
	}

	public byte[] encryptByPublicKeyServer(byte[] data, byte[] exponent, byte[] modulus)
			throws IOException, InvalidKeyException, NoSuchAlgorithmException, 
			NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, 
			IllegalBlockSizeException, BadPaddingException {
		
		BigInteger BINT_exponent = new BigInteger(exponent);
		BigInteger BINT_modulus = new BigInteger(modulus);
		
		RSAKey publicKey = new RSAKey(BINT_modulus, BINT_exponent);
		
		byte[] cipherData = RSA.rsaEncryptWithPublicKey(publicKey, data);
		
		return cipherData;
	}

	public byte[] getByteArrayFromFile(String filePath) throws IOException {
		InputStream is = context.getAssets().open(filePath);

		ByteArrayOutputStream buffer = new ByteArrayOutputStream();

		int nRead;
		byte[] data = new byte[1024];

		while ((nRead = is.read(data, 0, data.length)) != -1) {
			buffer.write(data, 0, nRead);
		}

		//buffer.flush();

		return buffer.toByteArray();
	}

	public  BigInteger getBigIntegerFromFile(String filePath) throws IOException {
		byte[] data = getByteArrayFromFile(filePath);
		return new BigInteger(data);
	}
}
